<?php
require('/var/www/html/beta.congdongeva.net/public_html/wp-blog-header.php');
require('generate.php');
$siteId = $argv[1];
/** 
 * getPosts return
 * Array(
 * 	links => array(),
 * 	detail => array(
 * 		0 => array(
 * 			'body' => '',
 * 			'title' => ''
 * 		)
 * 	)
 * )
 */
$tmpDir = realpath('./tmp');

$cateTamsu = 44;
$cateGiaitri = 49;
$cateCuoi = 57;

$postCate = $cateTamsu;
if($siteId == 6){
	$postCate = $cateTamsu;
}
if($siteId == 7){
	$postCate = $cateGiaitri;
}
if($siteId == 8){
	$postCate = $cateCuoi;
}

$data = getPosts($siteId);
if(!empty($data['detail'])){
	$arrReplace = array(' | Guu.VN', ' | jqk.vn');
	$i = 0;
	foreach($data['detail'] as $postData){
		// check duplicated URLs
		$url = mysql_real_escape_string($data['links'][$i]);
		$urlHash = md5($data['links'][$i]);

		$sql = "SELECT * FROM urls WHERE url='" . $url . "' OR url_hash='" . $urlHash . "'";
		$rs = mysql_query($sql, $linkCrawler);
		if(mysql_num_rows($rs) > 0){
			$i++;
			echo "Bypassing..\n";
			continue;
		}
		$postDate = date('Y-m-d H:i:s', time());
		$img = getFirstImg($postData['body']);
		$my_wp['image'] = null;
		if($img != ''){
			$imgPath = $tmpDir . '/' . basename($img);
			$imgData = Crawler::getUrlData($img);
			if(file_put_contents($imgPath, $imgData)){
				$my_wp['image'] = $imgPath;
				chmod($imgPath, 0777);
			}
		}
		$my_wp['post_title'] = $postData['title'];
		$my_wp['post_title'] = str_replace($arrReplace, '', $my_wp['post_title']);

		$my_wp['post_content'] = $postData['body'];
		$my_wp['post_status'] = 'pending';
		$my_wp['post_author'] = 7;
		//$my_wp['tags_input'] = array('tag 1', 'tag 2');
		$my_wp['tags_input'] = null;
		$my_wp['post_category'] = array(42, $postCate);
		$my_wp['post_date'] = $postDate;
		$my_wp['post_date_gmt'] = $postDate;
		echo wpInsertPost($my_wp);
		mysql_query("INSERT INTO urls(url, url_hash) VALUES('$url', '$urlHash')", $linkCrawler);
		echo "\n-------------\n";
		$i++;
	}
}
